﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;

namespace PROAD.atendimento.Relatorio
{
    public partial class relExcel : System.Web.UI.Page
    {
        DADOS.auxiliares.metEndereco metAux = new DADOS.auxiliares.metEndereco();

        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                CarregarDdl();
            }
        }

        protected void CarregarGrid()
        {
            var met = new DADOS.auxiliares.metRelatorio();
            gridExcel.DataSource = met.ExportExcel(Convert.ToInt32(ddlUf.SelectedValue));
            gridExcel.DataBind();

        }

        private void CarregarDdl()
        {
            ddlUf.DataSource = metAux.ListaUF();
            ddlUf.DataBind();
            //ddlUf.Items.Insert(0, new ListItem("Selecione uma UF", "0"));            
        }

        protected void btnExportar_Click(object sender, EventArgs e)
        {
            CarregarGrid();
            geraExcel(gridExcel,this,"export");
        }

        public void geraExcel(GridView gridView, Page oPage, string nomeArquivo)
        {
            try
            {
                System.Web.HttpContext.Current.Response.Clear();
                System.Web.HttpContext.Current.Response.ContentType = "application/vnd.ms-excel";
                System.Web.HttpContext.Current.Response.AddHeader("content-disposition", "attachment;filename= " + nomeArquivo + ".xls");

                System.Web.HttpContext.Current.Response.Charset = "";

                gridView.EnableViewState = false;

                System.IO.StringWriter oSW = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter oHtmlTw = new HtmlTextWriter(oSW);
                HtmlForm frm = new HtmlForm();

                oPage.Controls.Add(frm);
                frm.Controls.Add(gridView);
                frm.RenderControl(oHtmlTw);

                System.Web.HttpContext.Current.Response.Write(oSW.ToString());
                System.Web.HttpContext.Current.Response.End();
            }
            catch (Exception ex)
            {
                throw new Exception(ex.Message);
            }
        }
    }
}